package org.linlinjava.litemall.admin.service.order_manage;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.qcloudsms.SmsVoiceVerifyCodeSender;
import com.github.qcloudsms.SmsVoiceVerifyCodeSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.json.JSONException;
import org.linlinjava.litemall.admin.constant.CodeContent;
import org.linlinjava.litemall.admin.constant.PhoneCode;
import org.linlinjava.litemall.admin.enums.AdminErrorCode;
import org.linlinjava.litemall.admin.util.*;
import org.linlinjava.litemall.admin.vo.auth.BindingPhoneWechatVo;
import org.linlinjava.litemall.admin.vo.auth.UploadPassword;
import org.linlinjava.litemall.admin.vo.order_manage.CityRegion;
import org.linlinjava.litemall.admin.vo.order_manage.ProvinceRegion;
import org.linlinjava.litemall.admin.vo.order_manage.VillageRegion;
import org.linlinjava.litemall.admin.vo.shop.ClassiftChilden;
import org.linlinjava.litemall.admin.vo.shop.ClassifyParent;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallAdminMapper;
import org.linlinjava.litemall.db.dao.order_manage.AgedMallOrderMapper;
import org.linlinjava.litemall.db.domain.AgedmallClassify;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallRegion;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author wj
 * @date 2021/8/5 9:22
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AgedmallAuthService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AgedMallOrderMapper agedMallOrderMapper;

    @Resource
    private LitemallAdminService litemallAdminService;

    @Resource
    private LitemallAdminMapper litemallAdminMapper;

    public Object bindingCode(String phone, Integer type, Integer isVoice){
        Integer codeEffectiveTime=15;
        String phoneCountString="";
        String bindingPhone="";
        String templateId="";
        String[] params=new String[2];
        //登录绑定手机
        if(type==0){
             phoneCountString= PhoneCode.BINDING_PHONE_COUNT;
             bindingPhone=PhoneCode.BINDING_PHONE;
            templateId=CodeContent.BINGIND_PHONE_MESSAGE_TEMPLATEID;
        }
        //店铺审核
        else if(type==1){
            phoneCountString=PhoneCode.BINDING_PHONE_ADD_SHOP_COUNT;
            bindingPhone=PhoneCode.BINDING_PHONE_ADD_SHOP;
            templateId=CodeContent.ADD_SHOP_MESSAGE_TEMPLATEID;
        }
        //店铺删除
        else if(type==2){
            phoneCountString=PhoneCode.BINDING_PHONE_DEL_SHOP_COUNT;
            bindingPhone=PhoneCode.BINDING_PHONE_DEL_SHOP;
            templateId=CodeContent.DEL_SHOP_MESSAGE_TEMPLATEID;
        }
        //修改密码
        else if(type==3){
            phoneCountString=PhoneCode.CHANGE_PHONE_PASSWORD_COUNT;
            bindingPhone=PhoneCode.CHANGE_PHONE_PASSWORD;
            templateId=CodeContent.CHANGE_PASSWORD_MESSAGE_TEMPLATEID;
        }
        if(StringUtils.isNotBlank(phone)){
           String code= "";
           //TODO 加入redis
            String redisCode=stringRedisTemplate.opsForValue().get(bindingPhone+phone);
            String content="";
            if(StringUtils.isNotBlank(redisCode)){
                code=redisCode;
            }
            else{
                code=ShortCodeUtil.generateCode(4);
                stringRedisTemplate.opsForValue().set(bindingPhone+phone,code,codeEffectiveTime, TimeUnit.MINUTES);
            }
            params[0]=code;
            params[1]=codeEffectiveTime.toString();
            content=code;
            String CodeCount=stringRedisTemplate.opsForValue().get(phoneCountString+phone);
            if(StringUtils.isNotBlank(CodeCount)){
                CodeCount=(Integer.parseInt(CodeCount)+1)+"";
                stringRedisTemplate.opsForValue().set(phoneCountString+phone,CodeCount,0);
            }
            else{
                CodeCount="1";
                stringRedisTemplate.opsForValue().set(phoneCountString+phone,CodeCount,24,TimeUnit.HOURS);
            }
            //短信验证码
            if(isVoice==0){
                TencentSendUtil.sendSms(phone,templateId,params);
            }
            //语音验证码
            else if(isVoice==1){
                try {
                    SmsVoiceVerifyCodeSender vvcsender = new SmsVoiceVerifyCodeSender(TencentSmsConfig.appId,TencentSmsConfig.appKey);
                    vvcsender.send("86", phone,code, 2, "");

                } catch (Exception e) {
                    return ResponseUtil.fail(AdminErrorCode.PHONE_VOICE_CODE_ERROR.getCode(),AdminErrorCode.PHONE_VOICE_CODE_ERROR.getMessage());
                }
            }
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail(AdminErrorCode.BINGDING_PHONE_NOT_NULL.getCode(), AdminErrorCode.BINGDING_PHONE_NOT_NULL.getMessage());
    }

    public Object bindingPhoneWechat(BindingPhoneWechatVo bindingPhoneWechatVo){
        //TODO 微信开放平台申请下来后修改 shiro登录也要返回用户信息  这边强制修改密码，如果账号存在则绑定微信，如果不存在则创建账号绑定微信
        return ResponseUtil.ok();
    }


    public Object getCityList(){
        List<LitemallRegion> provinceList = agedMallOrderMapper.getCityList(null,1);
        List<LitemallRegion> cityList = agedMallOrderMapper.getCityList(null,2);
        List<LitemallRegion> villageList = agedMallOrderMapper.getCityList(null,3);
         List<ProvinceRegion> provinceBackList=new ArrayList<>();

        for (int i = 0; i <provinceList.size() ; i++) {
            ProvinceRegion provinceRegion=new ProvinceRegion();
            List<CityRegion> cityListMap = new ArrayList<>();
            for (int j = 0; j < cityList.size(); j++) {
                CityRegion cityRegion=new CityRegion();
                List<LitemallRegion> villageListFor = new ArrayList<>();
                for (int k = 0; k < villageList.size(); k++) {
                    if(cityList.get(j).getId().equals(villageList.get(k).getPid())){
                        villageListFor.add(villageList.get(k));
                    }
                }
                if(cityList.get(j).getPid().equals(provinceList.get(i).getId())){
                    cityRegion.setCity(cityList.get(j));
                    cityRegion.setVillage(villageListFor);
                    cityListMap.add(cityRegion);
                }
            }
            provinceRegion.setProvince(provinceList.get(i));
            provinceRegion.setCityRegion(cityListMap);
            provinceBackList.add(provinceRegion);
        }
        return ResponseUtil.ok(provinceBackList);
    }


    public Object twoLevelCityList(){
        List<LitemallRegion> parentClassify = agedMallOrderMapper.getCityList(null,1);
        List<LitemallRegion> childrenClassify = agedMallOrderMapper.getCityList(null,2);
        List<ClassifyParent> backParents=new ArrayList<>();
        for (int i = 0; i < parentClassify.size(); i++) {
            ClassifyParent classifyParent=new ClassifyParent();
            List<ClassiftChilden> childens=new ArrayList<>();
            for (int j = 0; j < childrenClassify.size(); j++) {
                if(childrenClassify.get(j).getPid().equals(parentClassify.get(i).getId())){
                    ClassiftChilden classiftChilden=new ClassiftChilden();
                    classiftChilden.setLabel(childrenClassify.get(j).getName());
                    classiftChilden.setValue(childrenClassify.get(j).getCode());
                    childens.add(classiftChilden);
                }
            }
            classifyParent.setLabel(parentClassify.get(i).getName());
            classifyParent.setValue(parentClassify.get(i).getCode());
            classifyParent.setChildren(childens);
            backParents.add(classifyParent);
        }
        return ResponseUtil.ok(backParents);
    }

    public Object updatePassword(UploadPassword uploadPassword){
        LitemallAdmin admin = litemallAdminService.findAdmin(uploadPassword.getPhone()).get(0);
        admin.setPassword(BcryptUtil.encode(uploadPassword.getPassword()));
        litemallAdminMapper.updateByPrimaryKeySelective(admin);
        return ResponseUtil.ok();
    }

}
